package com.jiangyifen.robot.core.tts;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.idst.nls.NlsClient;
import com.alibaba.idst.nls.NlsFuture;
import com.alibaba.idst.nls.event.NlsEvent;
import com.alibaba.idst.nls.event.NlsListener;
import com.alibaba.idst.nls.protocol.NlsRequest;
import com.jiangyifen.framework.util.UUIDUtil;
import com.jiangyifen.robot.core.Robot;


public class AliyunTTSClient implements NlsListener {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String ttsTempPath;

	private NlsClient client;

	private Robot robot;

	public AliyunTTSClient(String ttsTempPath) {
		this.ttsTempPath = ttsTempPath;

		this.client = new NlsClient();
		startup();
	}

	public void startup() {
		client.init();
	}

	public void shutdonw() {
		client.close();
	}

	public File tts(String text) {
		
		if(StringUtils.isBlank(text)){
			logger.error("TTS 内容为空");
			return null;
		}

		String filename = ttsTempPath + "/" + UUIDUtil.randomUUIDNoBar() + ".wav";
		File file = new File(filename);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		NlsRequest req = new NlsRequest();
		req.setAppKey("nls-service"); // 设置语音文件格式
		req.setTts_req(text, "8000"); // 传入测试文本，返回语音结果
		req.setTtsEncodeType("wav");// 返回语音数据格式，支持pcm,wav.alaw
		req.setTtsVolume(30); // 音量大小默认50，阈值0-100
		req.setTtsSpeechRate(0); // 语速，阈值-500~500
		req.setTtsBackgroundMusic(1, 0);// 背景音乐编号,偏移量
		req.authorize(robot.getRobotEntity().getAliyunAccessId(), robot.getRobotEntity().getAliyunAccessSecret());

		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			NlsFuture future = client.createNlsFuture(req, this); // 实例化请求,传入请求和监听器
			byte[] data;
			while ((data = future.read()) != null) {
				fileOutputStream.write(data, 0, data.length);
			}
			fileOutputStream.close();
			future.await(10000);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return file;

	}

	@Override
	public void onMessageReceived(NlsEvent e) {
		logger.debug("TTS onMessageReceived: " + JSON.toJSONString(e));
	}

	@Override
	public void onOperationFailed(NlsEvent e) {
		logger.debug("TTS onOperationFailed: " + JSON.toJSONString(e));
	}

	@Override
	public void onChannelClosed(NlsEvent e) {
		logger.debug("TTS onChannelClosed: " + JSON.toJSONString(e));
	}

	public Robot getRobot() {
		return robot;
	}

	public void setRobot(Robot robot) {
		this.robot = robot;
	}

}
